package com.sml.interceptors;

import com.sml.utils.JwtUtil;
import com.sml.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 接口请求（登录）拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 注入StringRedisTemplate
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 拦截器 在controller 执行之前执行
     * @param request   请求
     * @param response  响应
     * @param handler   请求头
     * @return true 放行 false 不放行
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String token = request.getHeader("Authorization");
        try {
            //令牌是否失效--redis存储的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            //获取redis中的token
            String redisToken = operations.get("token");
            if (redisToken==null) {
                //抛出异常，下面异常catch捕获401
                throw new RuntimeException("令牌失效");
            }
            //解析令牌
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    /**
     * 拦截器 在controller 执行之后执行 释放资源
     * @param request   请求
     * @param response  响应
     * @param handler   请求头
     * @param ex        异常
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //移除线程变量
        ThreadLocalUtil.remove();
    }
}
